<script setup lang="ts">
import { requiredCheck, singleIpCheck, validatePortFun } from "@/utils/verify";
import { ref, reactive } from "vue";
import { addData, editData, getInfo } from "@/api/modules/dynamic-camouflage/network-config";
import { getDataByPage as getFingerData } from "@/api/modules/resource/host-finger";
import { getDataByPage as getHsData } from "@/api/modules/resource/service";

interface Props {
  title?: string;
  rowData?: Object;
}

import SelectLinksInput from "@/components/SelectLinksInput/index.vue";

const props = withDefaults(defineProps<Props>(), {
  title: "配置网络",
  rowData: undefined
});
defineOptions({
  name: "UpdateForm" // 默认策略
});
import useUpdate from "@/hooks/useUpdate";
import { ifaceAll, ifacemodeUpdate } from "@/api/modules/dynamic-camouflage/line-config";
import SelectFingerHostData from "@/components/SelectFingerHostData/index.vue";
import { scfgBatchFing } from "@/api/modules/dynamic-camouflage/sentinel-config";
import { ElMessage } from "element-plus";
import SelectHserverData from "@/components/SelectHserverData/index.vue";

const emits = defineEmits(["success"]);
const { updateFormData, updateFormRef, updateFormRules, submit, showHandle, openHandle, closeHandle } = useUpdate({
  rules: {
    destport: [...requiredCheck("请输入端口"),
      {
        validator: (rule, value, callback) => {
          if (value.includes(";") && !value.startsWith(";")) {
            const ports = value.split(";");
            const pass = ports.every(port => validatePortFun(port));
            if (pass) {
              callback();
            } else {
              callback("端口格式错误");
            }
          }
          if (value.includes("-") && !value.startsWith("-") && !value.endsWith("-")) {
            const ports = value.split("-");
            let startPort = ports[0];
            let endPort = ports[1];
            const pass = ports.every(port => validatePortFun(port));
            if (pass && Number(startPort) < Number(endPort)) {
              callback();
            } else {
              callback("端口格式错误");
            }
          }
          if (validatePortFun(value)) {
            callback();
          } else {
            callback("端口格式错误");
          }
        }
      }],
    // fingers: [...requiredCheck("请选择指纹")],
    // hs: [...requiredCheck("请选择服务")]
  },
  defaultData: {
    type: "1",
    fingers: [],
    hs: []
  }
});
const ifaces = ref([]);

async function submitCb() {
  console.log("updateFormData", updateFormData);
  await submit({
    addApi: addData,
    updateApi: editData,
    sendData: {
      name: updateFormData.name,
      destport: updateFormData.destport,
      iprange: details.value.iprange,
      fingerip: updateFormData.fingers?updateFormData.fingers.map(item => item.ip).join():"",
      srvid: updateFormData.hs?updateFormData.hs.map(item => item.id).join(","):"",
      type: updateFormData.type || "",
      id: updateFormData?.id,
      description: updateFormData?.description,
      gateway: updateFormData?.gateway || ""
    }
  });
  emits("success");
}

async function selectFinger(data, id) {
  updateFormData.fingers = data.rowList;
}

async function selectHs(data, id) {
  console.log(data);
  updateFormData.hs = data;
}

const details = ref();
const pageData = reactive({
  fingerRemoteData: [],
  hsRemoteData: []
});

async function getData() {
  const [res1, res2] = await Promise.all([
    getFingerData({
      curpage: 0,
      perpage: 10000
    }),
    getHsData({
      pageNum: 0,
      pageSize: 10000
    })
  ]);
  pageData.fingerRemoteData = res1.data;
  let data = res2.result.data;
  let arr: any = [];
  data.forEach(item => {
    if (item[0] != 5) {
      let obj = JSON.parse(item[5]);
      let account = "-";
      let password = "-";
      console.log(obj);
      if (obj?.account) {
        account = obj.account[0]?.user;
        password = obj.account[0]?.password;
      }
      if (obj.srvid == 10) {
        password = obj.requirepass;
      }
      arr.push({
        id: item[item.length - 1].replace("/", ""),
        name: item[1],
        proto: item[2],
        port: item[3],
        grade: item[4],
        account,
        password,
        originData: item,
        srvid: obj.srvid,
        isCheck: false
      });
    }
    if (item[0] == 5) {
      let webArr = JSON.parse(item[5]);
      console.log("web==", webArr);
      webArr.app.forEach(val => {
        let priMap = new Map([
          ["1", "低"],
          ["2", "中"],
          ["3", "高"]
        ]);
        arr.push({
          id: val.id,
          name: val.name,
          proto: val.proto,
          port: val.port,
          grade: priMap.get(val.pri.toString()),
          account: "root",
          password: "123456",
          originData: item,
          type: val.type.toString(),
          srvid: webArr.srvid,
          file: val.file,
          isCheck: false
        });
      });
    }
  });
  console.log(res1, res2);
  pageData.hsRemoteData = arr;
  console.log("pageData", pageData);
}

async function openHandleCb() {
  openHandle({
    row: {
      ...props.rowData
    },
    id: props.rowData?.id
  });
  if (props.rowData?.id) {
    await getData();
    const res = await getInfo({
      id: props.rowData?.id
    });
    // const res = {
    //   id: "1",
    //   name: "线路1",
    //   iprange: "12.23.23.1/23",
    //   destport: "0-65535",
    //   fingerip: "0.0.0.1",
    //   srvid: ["SSH伪装服务", "TELNET伪装服务", "FTP伪装服务"],
    //   cfg: null,
    //   state: "1",
    //   uptime: "1756642310"
    // };
    details.value = res;
    updateFormData.destport = res?.destport || "";
    if (res.fingerip) {
      updateFormData.fingers = [pageData.fingerRemoteData.find(item => item.ip === res.fingerip) || ""];
    }
    if (res.srvid) {
      updateFormData.hs = pageData.hsRemoteData.filter(item =>
        res.srvid.find(val => {
          let text = item.name;
          if (text.includes(":")) {
            text = text.split(":")[0];
          }
          return val === text;
        })
      );
    }
  }
}
</script>

<template>
  <div class="update-form mg-r-sm" style="display: inline-block" @click="openHandleCb">
    <slot>
      <el-button type="primary">新增</el-button>
    </slot>
  </div>
  <base-dialog v-if="showHandle" @confirm="submitCb()" width="560px" :title="title" v-model="showHandle">
    <div class="details">
      <div class="details-main">
        <el-form ref="updateFormRef" :model="updateFormData" :rules="updateFormRules" label-width="80px" label-suffix="：">
          <el-form-item label="网段" prop="name">
            <span>{{ updateFormData.iprange }}/{{ updateFormData.iprangeSux }}</span>
          </el-form-item>
          <el-divider style="width: calc(100% - 40px); margin: 15px auto" />
          <el-form-item label="端口" prop="destport">
            <el-input style="width: 140px" placeholder="请输入端口" v-model="updateFormData.destport" />
          </el-form-item>
          <el-form-item class="mg-t-lg" label="" prop="finger">
            <SelectFingerHostData :noDialog="false" :maxMultipleNum="1" :defaultSelect="''" @select="d => selectFinger(d, updateFormData?.id)">
              <el-button type="primary">选择指纹</el-button>
            </SelectFingerHostData>
          </el-form-item>
          <el-form-item prop="fingers">
            <div style="width: 90%; border: 1px solid #80808094;height: 30px;line-height: 30px;padding-bottom: 5px;padding-left: 5px;">
              <el-tag
                closable
                @close="updateFormData.fingers.splice(index, 1)"
                v-for="(item, index) in updateFormData.fingers"
                :key="item"
              >
                {{ item.name }}
              </el-tag>
            </div>
            <el-input type="hidden" :model-value="updateFormData.fingers?.join()||''"></el-input>
          </el-form-item>
          <el-form-item label="">
            <SelectHserverData :defaultSelect="''" @select="d => selectHs(d, updateFormData?.id)">
              <el-button type="primary">选择服务</el-button>
            </SelectHserverData>
          </el-form-item>
          <el-form-item prop="hs">
            <div style="width: 90%; border: 1px solid #80808094; min-height: 150px; max-height: 350px; overflow-y: scroll">
              <el-tag
                class="mg-l-sm"
                closable
                @close="updateFormData.hs.splice(index, 1)"
                v-for="(item, index) in updateFormData.hs"
                :key="item"
              >
                {{ item.name }}
              </el-tag>
            </div>
            <el-input type="hidden" :model-value="updateFormData.hs?.join()||''"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <template #footer-more-button></template>
  </base-dialog>
</template>

<style lang="scss" scoped>
.network-range {
  display: flex;

  :deep(.el-form-item__content) {
    margin-left: 0px !important;
  }

  .network-center {
    height: 32px;
    align-items: center;
    display: flex;
  }
}
</style>
